#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <math.h>
#include <windows.h>

double simpson(double,double,int);
double right(double,double,int);
double left(double,double,int);
double trap(double,double,int);
void output(double,double,double,int,double,double,int);
double func(double);
char *getsym(void);
double get_double(void);
char get_char(void);
int main()
{
   HANDLE hconsole;
   CONSOLE_SCREEN_BUFFER_INFO SBINFO;
   hconsole = GetStdHandle(STD_OUTPUT_HANDLE);
   double a=0,b=0,I1=0,I2=0,I=0,e=0,E=0;
   int n,n1;
   char choise;
    printf("Enter lower limit: ");
    a = get_double();
    printf("Enter upper limit: ");
    b = get_double();
    printf("Choose your method: \n(s) for simpson\n(r) for right\n(l) for left\n(t) for trap\n: >");
    //choise = getsym();
    scanf("%s",&choise);
    if (choise == 'S' || choise == 's')
    {
        printf("Enter pair number of intervals: ");
        n=(int)get_double();
        while (n%2!=0)
        {
            system("cls");
            printf("wrong value: ");
            n=(int)get_double();
        }
    } else
    {
        printf("Enter number of intervals: ");
        n=(int)get_double();
    }
    n1=n;
    switch (choise)
    {
    case 's':
    case 'S':
        {
            I=simpson(a,b,n);
           // printf("In=",I);
            I1=I2=E=0;
            n=2;
            do {
                I1=simpson(a,b,n);
                n+=2;
                I2=simpson(a,b,n);
                E=fabs(I1-I2);
            } while (E>e);
            output(a,b,I,n1,I1,e,n);
        }
    }

   /* printf("Hello world!\n");
   char* tmp=getsym();
   double x = strtod(tmp,NULL);
   printf("\n%lf",x);
    //double c = strtod()*/
   // return 0;
}

char *getsym(void)
{
    char* a = malloc(sizeof(char)*128);
    scanf("%s",a);
    return(a);
}

double simpson(double a,double b,int n)
{
    double x,sum1=0,sum2=0,i=0,tmp=0,h=0;
    h=(b-a)/n;
    for (x=a+h;x<=b-h;x+=2*h)
    {
        sum1+=func(x);
    }
    for (x=a+2*h;x<=b-2*h;x+=2*h)
    {
        sum2+=func(x);
    }
    x=a;
    tmp=func(x)+4*sum1+2*sum2;
    x=b;
    tmp+=func(x);
    i=tmp*(h/3);
    return i;
}

double func(double x)
{
    double y;
    y=pow(x,2)+2*x;
    return y;
}

double get_double(void)
{
    double z;
    z = strtod(getsym(),NULL);
    return z;
}
char get_char(void)
{
    char z;
    scanf("%s",&z);
    return(z);
}

void output(double a,double b,double e,int n1,double I,double I1,int n)
{
    printf("I= ",I);
    printf("\nn=",n1);
    printf("\nI1",I1);
    printf("\nn1=",n);
}
